<template>
  <div class="test-paper">
    <!-- 顶部信息栏 -->
    <div class="test-paper__header">
      <div class="header-left">
        <h2 class="test-title">{{ testPaper.title || '测试试卷' }}</h2>
        <div class="test-info">
          <span class="info-item">总题数：{{ testPaper.totalQuestionNum || 0 }}</span>
          <span class="info-item">测试时间：{{ formatTime(remainingTime) }}</span>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" size="small" @click="submitTest" :disabled="isSubmitting">
          {{ isSubmitting ? '提交中...' : '提交试卷' }}
        </el-button>
      </div>
    </div>

    <!-- 试卷内容 -->
    <div v-loading="loading" class="test-paper__content">
      <template v-if="testPaper.testId">
        <!-- 英译中题目 -->
        <div v-if="testPaper.etcTranslation?.length" class="question-section">
          <h3 class="section-title">英译中（{{ testPaper.etcTranslation.length }}题）</h3>
          <div class="question-grid">
            <div
              v-for="(question, index) in testPaper.etcTranslation"
              :key="`etc-${question.wordId}`"
              class="question-item"
            >
              <div class="question-header">
                <span class="question-number">{{ index + 1 }}.</span>
                <span class="question-text">{{ question.spelling }}</span>
              </div>
              <div class="answer-options">
                <el-radio-group
                  v-model="userAnswers[`etc-${question.wordId}`]"
                  class="answer-group-grid"
                  size="small"
                >
                  <el-radio
                    v-for="(answer, answerIndex) in question.answers"
                    :key="`etc-${question.wordId}-${answerIndex}`"
                    :label="answerIndex"
                    class="answer-option-grid"
                    size="small"
                  >
                    {{ answer.meaning }}
                  </el-radio>
                </el-radio-group>
              </div>
            </div>
          </div>
        </div>

        <!-- 中译英题目 -->
        <div v-if="testPaper.cteTranslation?.length" class="question-section">
          <h3 class="section-title">中译英（{{ testPaper.cteTranslation.length }}题）</h3>
          <div class="question-grid">
            <div
              v-for="(question, index) in testPaper.cteTranslation"
              :key="`cte-${question.wordId}`"
              class="question-item"
            >
              <div class="question-header">
                <span class="question-number">{{ etcCount + index + 1 }}.</span>
                <span class="question-text">{{ question.meaning }}</span>
              </div>
              <div class="answer-options">
                <el-radio-group
                  v-model="userAnswers[`cte-${question.wordId}`]"
                  class="answer-group-grid"
                  size="small"
                >
                  <el-radio
                    v-for="(answer, answerIndex) in question.answers"
                    :key="`cte-${question.wordId}-${answerIndex}`"
                    :label="answerIndex"
                    class="answer-option-grid"
                    size="small"
                  >
                    {{ answer.spelling }}
                  </el-radio>
                </el-radio-group>
              </div>
            </div>
          </div>
        </div>

        <!-- 听力理解题目 -->
        <div v-if="testPaper.hearingTranslation?.length" class="question-section">
          <h3 class="section-title">听力理解（{{ testPaper.hearingTranslation.length }}题）</h3>
          <div class="question-grid">
            <div
              v-for="(question, index) in testPaper.hearingTranslation"
              :key="`hearing-${question.wordId}`"
              class="question-item"
            >
              <div class="question-header">
                <span class="question-number">{{ etcCount + cteCount + index + 1 }}.</span>
                <el-button
                  type="primary"
                  size="small"
                  :icon="VideoPlay"
                  @click="playAudio(question.spelling)"
                  class="play-button"
                >
                  播放
                </el-button>
              </div>
              <div class="answer-options">
                <el-radio-group
                  v-model="userAnswers[`hearing-${question.wordId}`]"
                  class="answer-group-grid"
                  size="small"
                >
                  <el-radio
                    v-for="(answer, answerIndex) in question.answers"
                    :key="`hearing-${question.wordId}-${answerIndex}`"
                    :label="answerIndex"
                    class="answer-option-grid"
                    size="small"
                  >
                    {{ answer.meaning }}
                  </el-radio>
                </el-radio-group>
              </div>
            </div>
          </div>
        </div>
      </template>

      <!-- 空状态 -->
      <div v-else-if="!loading" class="empty-state">
        <el-empty description="暂无试卷内容" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import TASK_API from '@/api/dcyx/task.api'
import { VideoPlay } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDcyxTestCenterStoreHook, useDcyxUserStoreHook } from '@/store'
import type { UnitTestPaper, UserAnswer, SubmitTestPaperPayload } from '@/api/dcyx/test-center.api'

defineOptions({
  name: 'TestPaper',
  inheritAttrs: false,
})

const route = useRoute()
const router = useRouter()
const testCenterStore = useDcyxTestCenterStoreHook()
const userStore = useDcyxUserStoreHook()

// 响应式数据
const loading = ref(false)
const isSubmitting = ref(false)
const testPaper = ref<UnitTestPaper>({} as UnitTestPaper)
const userAnswers = ref<Record<string, number>>({})
const remainingTime = ref(0) // 剩余时间（秒）
const timer = ref<number | null>(null)

// 计算属性
const etcCount = computed(() => testPaper.value.etcTranslation?.length || 0)
const cteCount = computed(() => testPaper.value.cteTranslation?.length || 0)
const hearingCount = computed(() => testPaper.value.hearingTranslation?.length || 0)

// 格式化时间显示
const formatTime = (seconds: number) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 打乱数组顺序的函数
function shuffleArray<T>(array: T[]): T[] {
  const shuffled = [...array]
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
  }
  return shuffled
}

// 打乱题目选项顺序，并记录原始索引映射
function shuffleQuestionAnswers(questions: any[]) {
  return questions.map(question => {
    const originalAnswers = [...question.answers]
    const shuffledAnswers = shuffleArray(originalAnswers)

    // 创建原始索引到新索引的映射
    const indexMapping: Record<number, number> = {}
    shuffledAnswers.forEach((answer, newIndex) => {
      const originalIndex = originalAnswers.findIndex(orig => orig === answer)
      indexMapping[originalIndex] = newIndex
    })

    return {
      ...question,
      answers: shuffledAnswers,
      originalIndexMapping: indexMapping
    }
  })
}

// 重置组件状态
function resetComponentState() {
  // 清理定时器
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }

  // 重置状态
  isSubmitting.value = false
  testPaper.value = {} as UnitTestPaper
  userAnswers.value = {}
  remainingTime.value = 0

  // 注意：不重置loading状态，让它在数据加载过程中保持显示
}

// 获取试卷内容
async function fetchTestPaper() {
  const unitId = Number(route.params.unitId)
  console.log('开始获取试卷内容, unitId:', unitId)

  if (!unitId) {
    ElMessage.error('单元ID不存在')
    router.back()
    return
  }

  try {
    loading.value = true
    console.log('正在加载试卷数据...')
    const paper = await testCenterStore.fetchTestPaper(unitId)

    // 打乱题目选项顺序
    const shuffledPaper = {
      ...paper,
      etcTranslation: shuffleQuestionAnswers(paper.etcTranslation || []),
      cteTranslation: shuffleQuestionAnswers(paper.cteTranslation || []),
      hearingTranslation: shuffleQuestionAnswers(paper.hearingTranslation || [])
    }

    testPaper.value = shuffledPaper
    console.log('试卷数据加载成功:', paper.title)

    // 重置用户答案
    userAnswers.value = {}

    // 初始化倒计时
    remainingTime.value = parseInt(paper.second) || 1800
    startTimer()
  } catch (error) {
    console.error('获取试卷内容失败:', error)
    ElMessage.error('获取试卷内容失败')
    router.back()
  } finally {
    loading.value = false
    console.log('试卷数据加载完成')
  }
}

// 开始倒计时
function startTimer() {
  if (timer.value) {
    clearInterval(timer.value)
  }
  
  timer.value = window.setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--
    } else {
      // 时间到，自动提交
      clearInterval(timer.value!)
      ElMessage.warning('考试时间已到，系统将自动提交试卷')
      submitTest()
    }
  }, 1000)
}

// 播放音频
async function playAudio(word: string) {
  try {
    // 停止之前的音频
    if ((window as any).wordAudio) {
      ;(window as any).wordAudio.pause()
      ;(window as any).wordAudio.currentTime = 0
    }

    // 获取音频URL并播放
    const audioUrl = await testCenterStore.playWordAudio(word)
    ;(window as any).wordAudio = new window.Audio(audioUrl)
    ;((window as any).wordAudio as HTMLAudioElement).play()

    // 播放结束后清理URL
    ;((window as any).wordAudio as HTMLAudioElement).onended = () => {
      URL.revokeObjectURL(audioUrl)
    }
  } catch (error) {
    console.error('播放音频失败:', error)
    ElMessage.error('播放音频失败')
  }
}

// 提交试卷
async function submitTest() {
  try {
    await ElMessageBox.confirm('确定要提交试卷吗？提交后将无法修改答案。', '确认提交', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    isSubmitting.value = true

    // 停止倒计时
    if (timer.value) {
      clearInterval(timer.value)
    }

    // 准备提交数据
    const userAnswers = prepareUserAnswers()
    const testResult = calculateTestResult()
    const submitData: SubmitTestPaperPayload = {
      testId: testPaper.value.testId,
      userId: parseInt(String(userStore.userInfo.id || '0')),
      unitId: Number(route.params.unitId),
      score: testResult.score,
      time_spent: parseInt(testPaper.value.second) - remainingTime.value,
      wrong_word_ids: testResult.wrongWordIds.join(','),
      right_word_ids: testResult.rightWordIds.join(','),
      unchoose_word_ids: testResult.unchooseWordIds.join(','),
      userAnswers,
    }

    // 调用提交试卷的API
    const result = await testCenterStore.submitTestPaper(submitData)
    ElMessage.success(result.msg || '试卷提交成功')

    // 轻量引导：刷新任务项并根据 Gate 状态返回任务页或主页
    const lastId = Number(localStorage.getItem('LAST_TASK_ITEM_ID') || '0')
    try {
      if (lastId > 0) {
        await TASK_API.refreshItem(lastId)
      }
    } catch {/* 忽略刷新异常 */}

    let hasPending = false
    try {
      const gate = await TASK_API.getGateTodayStatus()
      hasPending = !!gate?.hasPending
      // 更新本地 Gate TTL 缓存，减少后续重复校验
      localStorage.setItem('GATE_TODAY_STATUS', String(hasPending))
      localStorage.setItem('GATE_TODAY_STATUS_TS', String(Date.now()))
    } catch {/* 忽略异常并走默认分支 */}

    if (hasPending) {
      ElMessage.info('已提交，返回今日任务继续完成')
      router.replace('/gate/tasks')
    } else {
      // 若不是从任务页进入（无 lastId），保留原有跳回测试中心的习惯
      if (lastId > 0) {
        ElMessage.success('今日任务已完成，返回主页')
        router.replace('/work/word-training')
      } else {
        router.push({ path: '/work/test-center', query: { refresh: Date.now().toString() } })
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交试卷失败:', error)
      ElMessage.error('提交试卷失败')
    }
  } finally {
    isSubmitting.value = false
  }
}

// 准备用户答案数据
function prepareUserAnswers(): UserAnswer[] {
  const answers: UserAnswer[] = []

  // 处理英译中答案
  testPaper.value.etcTranslation?.forEach((question) => {
    const userAnswerIndex = userAnswers.value[`etc-${question.wordId}`]
    if (userAnswerIndex !== undefined) {
      const isCorrect = question.answers[userAnswerIndex]?.correct === 1
      answers.push({
        wordId: question.wordId,
        questionType: 'etcTranslation',
        userAnswerIndex,
        isCorrect,
      })
    }
  })

  // 处理中译英答案
  testPaper.value.cteTranslation?.forEach((question) => {
    const userAnswerIndex = userAnswers.value[`cte-${question.wordId}`]
    if (userAnswerIndex !== undefined) {
      const isCorrect = question.answers[userAnswerIndex]?.correct === 1
      answers.push({
        wordId: question.wordId,
        questionType: 'cteTranslation',
        userAnswerIndex,
        isCorrect,
      })
    }
  })

  // 处理听力理解答案
  testPaper.value.hearingTranslation?.forEach((question) => {
    const userAnswerIndex = userAnswers.value[`hearing-${question.wordId}`]
    if (userAnswerIndex !== undefined) {
      const isCorrect = question.answers[userAnswerIndex]?.correct === 1
      answers.push({
        wordId: question.wordId,
        questionType: 'hearingTranslation',
        userAnswerIndex,
        isCorrect,
      })
    }
  })

  return answers
}

// 计算测试结果
function calculateTestResult() {
  const result = {
    testTime: new Date().toISOString(),
    testDuration: parseInt(testPaper.value.second) - remainingTime.value,
    totalQuestions: etcCount.value + cteCount.value + hearingCount.value,
    correctAnswers: 0,
    wrongAnswers: 0,
    unansweredQuestions: 0,
    score: 0,
    rightWordIds: [] as string[],
    wrongWordIds: [] as string[],
    unchooseWordIds: [] as string[],
    correctWords: [] as any[],
    wrongWords: [] as any[],
    unansweredWords: [] as any[],
    questionTypeStats: {
      etcTranslation: { correct: 0, wrong: 0, unanswered: 0 },
      cteTranslation: { correct: 0, wrong: 0, unanswered: 0 },
      hearingTranslation: { correct: 0, wrong: 0, unanswered: 0 },
    }
  }

  // 统计英译中结果
  testPaper.value.etcTranslation?.forEach((question) => {
    const userAnswer = userAnswers.value[`etc-${question.wordId}`]
    if (userAnswer !== undefined) {
      const isCorrect = question.answers[userAnswer]?.correct === 1
      if (isCorrect) {
        result.correctAnswers++
        result.questionTypeStats.etcTranslation.correct++
        result.correctWords.push({ ...question, questionType: 'etcTranslation' })
        result.rightWordIds.push(question.wordId)
      } else {
        result.wrongAnswers++
        result.questionTypeStats.etcTranslation.wrong++
        result.wrongWords.push({ ...question, questionType: 'etcTranslation', userAnswer })
        result.wrongWordIds.push(question.wordId)
      }
    } else {
      result.unansweredQuestions++
      result.questionTypeStats.etcTranslation.unanswered++
      result.unansweredWords.push({ ...question, questionType: 'etcTranslation' })
      result.unchooseWordIds.push(question.wordId)
    }
  })

  // 统计中译英结果
  testPaper.value.cteTranslation?.forEach((question) => {
    const userAnswer = userAnswers.value[`cte-${question.wordId}`]
    if (userAnswer !== undefined) {
      const isCorrect = question.answers[userAnswer]?.correct === 1
      if (isCorrect) {
        result.correctAnswers++
        result.questionTypeStats.cteTranslation.correct++
        result.correctWords.push({ ...question, questionType: 'cteTranslation' })
        result.rightWordIds.push(question.wordId)
      } else {
        result.wrongAnswers++
        result.questionTypeStats.cteTranslation.wrong++
        result.wrongWords.push({ ...question, questionType: 'cteTranslation', userAnswer })
        result.wrongWordIds.push(question.wordId)
      }
    } else {
      result.unansweredQuestions++
      result.questionTypeStats.cteTranslation.unanswered++
      result.unansweredWords.push({ ...question, questionType: 'cteTranslation' })
      result.unchooseWordIds.push(question.wordId)
    }
  })

  // 统计听力理解结果
  testPaper.value.hearingTranslation?.forEach((question) => {
    const userAnswer = userAnswers.value[`hearing-${question.wordId}`]
    if (userAnswer !== undefined) {
      const isCorrect = question.answers[userAnswer]?.correct === 1
      if (isCorrect) {
        result.correctAnswers++
        result.questionTypeStats.hearingTranslation.correct++
        result.correctWords.push({ ...question, questionType: 'hearingTranslation' })
        result.rightWordIds.push(question.wordId)
      } else {
        result.wrongAnswers++
        result.questionTypeStats.hearingTranslation.wrong++
        result.wrongWords.push({ ...question, questionType: 'hearingTranslation', userAnswer })
        result.wrongWordIds.push(question.wordId)
      }
    } else {
      result.unansweredQuestions++
      result.questionTypeStats.hearingTranslation.unanswered++
      result.unansweredWords.push({ ...question, questionType: 'hearingTranslation' })
      result.unchooseWordIds.push(question.wordId)
    }
  })

  // 计算分数
  result.score = result.totalQuestions > 0 ? Math.round((result.correctAnswers / result.totalQuestions) * 100) : 0

  return result
}

// 页面离开前确认
const beforeUnloadHandler = (event: BeforeUnloadEvent) => {
  event.preventDefault()
  event.returnValue = '确定要离开吗？未提交的答案将会丢失。'
}

// 监听路由参数变化
watch(
  () => route.params.unitId,
  (newUnitId, oldUnitId) => {
    if (newUnitId && newUnitId !== oldUnitId) {
      console.log('单元ID变化:', oldUnitId, '->', newUnitId)
      // 重置组件状态
      resetComponentState()
      // 重新获取试卷数据
      fetchTestPaper()
    }
  },
  { immediate: false }
)

onMounted(() => {
  fetchTestPaper()
  // 添加页面离开前的确认
  window.addEventListener('beforeunload', beforeUnloadHandler)
})

onUnmounted(() => {
  // 清理定时器
  if (timer.value) {
    clearInterval(timer.value)
  }
  // 移除页面离开前的确认
  window.removeEventListener('beforeunload', beforeUnloadHandler)
})
</script>

<style lang="scss" scoped>
.test-paper {
  min-height: 100vh;
  background-color: var(--el-bg-color-page);
  padding: 20px;

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background-color: #fff;
    border-radius: 6px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .header-left {
      flex: 1;

      .test-title {
        margin: 0 0 6px 0;
        font-size: 18px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .test-info {
        display: flex;
        gap: 16px;

        .info-item {
          font-size: 12px;
          color: var(--el-text-color-regular);
        }
      }
    }

    .header-right {
      flex-shrink: 0;
    }
  }

  &__content {
    background-color: #fff;
    border-radius: 6px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }
}

.question-section {
  margin-bottom: 24px;

  &:last-child {
    margin-bottom: 0;
  }

  .section-title {
    margin: 0 0 16px 0;
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    border-bottom: 2px solid var(--el-color-primary);
    padding-bottom: 6px;
  }
}

// 网格布局 - 一行两道题
.question-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;

  .question-item {
    padding: 14px;
    border: 1px solid var(--el-border-color-light);
    border-radius: 6px;
    transition: all 0.3s ease;

    &:hover {
      border-color: var(--el-color-primary-light-7);
      box-shadow: 0 2px 8px rgba(64, 128, 255, 0.1);
    }

    .question-header {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      gap: 8px;

      .question-number {
        font-weight: 600;
        color: var(--el-color-primary);
        min-width: 20px;
        font-size: 14px;
      }

      .question-text {
        font-size: 14px;
        font-weight: 500;
        color: var(--el-text-color-primary);
        flex: 1;
      }

      .play-button {
        flex-shrink: 0;
      }
    }

    .answer-options {
      .answer-group-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 8px;

        .answer-option-grid {
          padding: 8px 12px;
          border: 1px solid var(--el-border-color-light);
          border-radius: 4px;
          transition: all 0.3s ease;
          cursor: pointer;

          &:hover {
            border-color: var(--el-color-primary-light-7);
            background-color: var(--el-color-primary-light-9);
          }

          &.is-checked {
            border-color: var(--el-color-primary);
            background-color: var(--el-color-primary-light-8);
          }

          :deep(.el-radio__label) {
            font-size: 12px;
            line-height: 1.4;
            word-break: break-all;
          }
        }
      }
    }
  }
}

// 保留原有的列表布局作为备用
.question-list {
  .question-item {
    margin-bottom: 16px;
    padding: 14px;
    border: 1px solid var(--el-border-color-light);
    border-radius: 6px;
    transition: all 0.3s ease;

    &:hover {
      border-color: var(--el-color-primary-light-7);
      box-shadow: 0 2px 8px rgba(64, 128, 255, 0.1);
    }

    &:last-child {
      margin-bottom: 0;
    }

    .question-header {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      gap: 8px;

      .question-number {
        font-weight: 600;
        color: var(--el-color-primary);
        min-width: 20px;
        font-size: 14px;
      }

      .question-text {
        font-size: 14px;
        font-weight: 500;
        color: var(--el-text-color-primary);
        flex: 1;
      }

      .play-button {
        flex-shrink: 0;
      }
    }

    .answer-options {
      .answer-group {
        display: flex;
        flex-direction: column;
        gap: 8px;

        .answer-option {
          padding: 8px 12px;
          border: 1px solid var(--el-border-color-light);
          border-radius: 4px;
          transition: all 0.3s ease;
          cursor: pointer;

          &:hover {
            border-color: var(--el-color-primary-light-7);
            background-color: var(--el-color-primary-light-9);
          }

          &.is-checked {
            border-color: var(--el-color-primary);
            background-color: var(--el-color-primary-light-8);
          }

          :deep(.el-radio__label) {
            font-size: 12px;
            line-height: 1.4;
          }
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

// 响应式设计
@media (max-width: 768px) {
  .test-paper {
    padding: 12px;

    &__header {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;

      .header-left {
        text-align: center;

        .test-info {
          justify-content: center;
        }
      }
    }

    &__content {
      padding: 16px;
    }
  }

  // 小屏幕时改为单列布局
  .question-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .question-item {
    .question-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;

      .play-button {
        align-self: flex-end;
      }
    }

    .answer-options {
      .answer-group-grid {
        grid-template-columns: 1fr;
        gap: 6px;
      }
    }
  }
}
</style>
